package com.yy.QSManage.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yy.QSManage.dao.FaSysDataSourceMapper;
import com.yy.QSManage.dao.FaSysGridMapper;
import com.yy.QSManage.model.dto.FieldDto;
import com.yy.QSManage.model.entity.FaSysDataSource;
import com.yy.QSManage.model.entity.FaSysGrid;
import com.yy.QSManage.model.entity.FaSysSettings;
import com.yy.QSManage.service.FaSysGridService;
import com.yy.QSManage.service.FaSysSettingsService;
import com.yy.QSManage.service.base.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class FaSysGridServiceImpl extends BaseServiceImpl<FaSysGridMapper, FaSysGrid> implements FaSysGridService{

    @Autowired
    private FaSysGridMapper faSysGridMapper;
    @Autowired
    private FaSysDataSourceMapper dataSourceMapper;
    @Autowired
    private FaSysSettingsService settingsService;

    @Override
    public List<String> tables() {
        return faSysGridMapper.tables();
    }

    @Override
    public FaSysGrid initialize(FaSysGrid faSysGrid) {
        // 初始化表格和字段配置
        // 获取模版
        FaSysSettings tableJson = settingsService.getByParam(FaSysSettings::getKeyName, "GRID_TABLE_JSON");
        FaSysSettings fieldJson = settingsService.getByParam(FaSysSettings::getKeyName, "GRID_FIELD_JSON");
        FaSysSettings addJson = settingsService.getByParam(FaSysSettings::getKeyName, "GRID_ADD_JSON");
        FaSysSettings editJson = settingsService.getByParam(FaSysSettings::getKeyName, "GRID_EDIT_JSON");
        FaSysSettings queryJson = settingsService.getByParam(FaSysSettings::getKeyName, "GRID_QUERY_JSON");
        FaSysSettings importJson = settingsService.getByParam(FaSysSettings::getKeyName, "GRID_IMPORT_JSON");
        FaSysSettings exportJson = settingsService.getByParam(FaSysSettings::getKeyName, "GRID_EXPORT_JSON");
        // 转为JSON对象
        JSONObject fieldJsonObj = JSONUtil.parseObj(fieldJson.getValue());
        JSONObject addJsonObj = JSONUtil.parseObj(addJson.getValue());
        JSONObject editJsonObj = JSONUtil.parseObj(editJson.getValue());
        JSONObject queryJsonObj = JSONUtil.parseObj(queryJson.getValue());
        JSONObject importJsonObj = JSONUtil.parseObj(importJson.getValue()).getJSONArray("fields").getJSONObject(0);
        JSONObject exportJsonObj = JSONUtil.parseObj(exportJson.getValue());
        // 初始化变量
        JSONArray fieldJsonObjs = new JSONArray();
        JSONArray addJsonObjs = new JSONArray();
        JSONArray editJsonObjs = new JSONArray();
        JSONArray queryJsonObjs = new JSONArray();
        JSONArray importJsonObjs = new JSONArray();
        JSONArray exportJsonObjs = new JSONArray();
        // 获取数据源信息
        FaSysDataSource dataSource = dataSourceMapper.selectById(faSysGrid.getDataSourceId());
        // 查询表格字段信息
        List<FieldDto> fields = dataSourceMapper.fields(dataSource.getSource());
        for (int i = 0; i < fields.size(); i++) {
            FieldDto fieldDto = fields.get(i);
            // 克隆，否则会引用同一个JSON对象
            JSONObject fieldJsonObjClon = clon(fieldJsonObj);
            JSONObject addJsonObjClon = clon(addJsonObj);
            JSONObject editJsonObjClon = clon(editJsonObj);
            JSONObject queryJsonObjClon = clon(queryJsonObj);
            JSONObject importJsonObjClon = clon(importJsonObj);
            JSONObject exportJsonObjClon = clon(exportJsonObj);
            // 下划线格式改驼峰
            String field = StrUtil.toCamelCase(fieldDto.getColumn());
            // 列表字段配置
            fieldJsonObjClon.set("id", i+1)
                    .set("field", field)
                    .set("label", fieldDto.getComment())
                    .getJSONObject("type").set("value", fieldDto.getDataType());

            // 特殊字段处理
            switch (fieldDto.getColumn()){
                case "extend":
                    // 扩展字段排除
                    break;
                case "id":
                case "create_time":
                case "create_user":
                case "update_time":
                case "update_user":
                case "is_delete":
                    fieldJsonObjClon.set("isShow", false);
                    break;
                default:
                    // 添加字段配置
                    addJsonObjClon.set("id", addJsonObjs.size())
                            .set("field", field)
                            .set("label", fieldDto.getComment())
                            .set("gridField", field);
                    addJsonObjClon.getJSONObject("type").set("value", fieldDto.getDataType());
                    // 编辑字段配置
                    editJsonObjClon.set("id", editJsonObjs.size())
                            .set("field", field)
                            .set("label", fieldDto.getComment())
                            .set("gridField", field);
                    editJsonObjClon.getJSONObject("type").set("value", fieldDto.getDataType());
                    // 搜索字段配置
                    queryJsonObjClon.set("id", queryJsonObjs.size())
                            .set("field", field)
                            .set("label", fieldDto.getComment())
                            .set("gridField", field);
                    // 导入字段配置
                    importJsonObjClon.set("id", importJsonObjs.size())
                            .set("field", field)
                            .set("alias", fieldDto.getComment())
                            .set("gridField", field);
                    // 导出字段配置
                    exportJsonObjClon.set("id", exportJsonObjs.size())
                            .set("field", field)
                            .set("alias", fieldDto.getComment())
                            .set("gridField", field);
                    addJsonObjs.add(addJsonObjClon);
                    editJsonObjs.add(editJsonObjClon);
                    queryJsonObjs.add(queryJsonObjClon);
                    importJsonObjs.add(importJsonObjClon);
                    exportJsonObjs.add(exportJsonObjClon);
                    break;
            }
            fieldJsonObjs.add(fieldJsonObjClon);
        }
        faSysGrid.setTableJson(tableJson.getValue())
                .setFieldJson(fieldJsonObjs.toString())
                .setAddJson(addJsonObjs.toString())
                .setEditJson(editJsonObjs.toString())
                .setQueryJson(queryJsonObjs.toString())
                .setImportJson(JSONUtil.parseObj(importJson.getValue()).set("fields", importJsonObjs).toString())
                .setExportJson(exportJsonObjs.toString());
        return faSysGrid;
    }

    @Override
    public void getImportField(String id, HashMap<String, String> aliasMap, List<JSONObject> fieldList) {
        // 获取网格信息
        FaSysGrid grid = getById(id);
        // 获取导入配置
        String importJson = grid.getImportJson();
        JSONObject importJsonObj = JSONUtil.parseObj(importJson);
        JSONArray fields = importJsonObj.getJSONArray("fields");
        for (Object field : fields) {
            JSONObject fieldJsonObj = (JSONObject)field;
            String isShow = fieldJsonObj.getStr("isShow");
            if(isShow.equals("true")){
                if(Objects.nonNull(aliasMap)){
                    aliasMap.put(fieldJsonObj.getStr("alias"), fieldJsonObj.getStr("field"));
                }
                if(Objects.nonNull(fieldList)){
                    fieldList.add(fieldJsonObj);
                }
            }
        }
    }

    @Override
    public void getExportField(String id, HashMap<String, String> aliasMap) {
        // 获取网格信息
        FaSysGrid grid = getById(id);
        // 获取导入配置
        String exportJson = grid.getExportJson();
        JSONArray fields = new JSONArray(exportJson);
        for (Object field : fields) {
            JSONObject fieldJsonObj = (JSONObject)field;
            String isShow = fieldJsonObj.getStr("isShow");
            if(isShow.equals("true")){
                if(Objects.nonNull(aliasMap)){
                    aliasMap.put(fieldJsonObj.getStr("field"),fieldJsonObj.getStr("alias"));
                }
            }
        }
    }

    @Override
    public List<FieldDto> fields(String id) {
        FaSysGrid grid = getById(id);
        // 获取数据源信息
        FaSysDataSource dataSource = dataSourceMapper.selectById(grid.getDataSourceId());
        // 查询表格字段信息
        return dataSourceMapper.fields(dataSource.getSource());
    }

    private JSONObject clon(JSONObject jsonObject){
        return JSONUtil.parseObj(jsonObject.toString());
    }
}
